<?php


namespace App\Http\Controllers\Home;


use App\Http\Controllers\Controller;
use App\Http\Status;
use Illuminate\Support\Facades\DB;

class CategoryController extends Controller
{
    public function getCategory()
    {
        $root_data = DB::table("lar_category")->where([
            "parent_id" =>  0
        ])->get();

        // 1.把所有的根遍历出来
        $category_list = [];
        foreach ($root_data as $root) {
            // 2.遍历父级别等于根的就是对应的二级
            $child_data = DB::table("lar_category")->where([
                "parent_id" =>  $root->id
            ])->get();

            $child_item_list = [];
            foreach ($child_data as $child_item) {
                $child_item_data = [
                    "child_id"  =>  $child_item->id,
                    "name"      =>  $child_item->name,
                    "image"     =>  $child_item->image
                ];
                array_push($child_item_list, $child_item_data);
            }

            $root_category = [
                "cate_id"       =>  $root->id,
                "cate_name"     =>  $root->name,
                "children"      =>  $child_item_list
            ];

            // 把按指定格式组装好的数据放在最终要返回的列表里
            array_push($category_list, $root_category);
        }

        return response()->json([
            "code"  =>  Status::$OK,
            "msg"   =>  Status::$OK_MSG,
            "data"  =>  $category_list
        ]);
    }
}
